Python中查看对象的所有属性和方法以及查看属性是否存在

您所在的位置:网站首页 python 看变量类型 Python中查看对象的所有属性和方法以及查看属性是否存在

Python中查看对象的所有属性和方法以及查看属性是否存在

2024-06-15 18:35| 来源: 网络整理| 查看: 265

Python中查看对象的所有属性和方法以及查看属性是否存在 作者:爱编程的小金毛球球 日期:2023年12月3日

Python提供许多的内置函数和模块来帮助开发人员查看对象的所有属性,例如:dir(),vars(),__dict__等。

dir()函数查看对象的所有属性

dir()是Python内置函数之一,帮助检查给定对象的所有方法和属性,包含方法、变量、函数等。dir()函数用于枚举一个类或实例中的所有属性和方法。

语法:dir([object=None]) #!/usr/bin/env python3 # 定义一个字符串变量,并查看其所有属性和方法 sweet_talk= 'i love u' print(dir(sweet_talk)) # 输出(list): ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 使用vars()函数和__dict__属性来查看对象的所有属性

与dir()函数不同,vars()函数和__dict__属性是专门用来查看对象的属性和值,我们可以使用vars()函数来查看用户自定义对象或内置对象的属性,使用__dict__属性来查看给定对象的所有属性。vars()函数和__dict__属性使用方法类似。

语法:vars([object=None]) # 定义一个Student类,属性包括name、sex、age class Student: def __init__(self, name, sex, age): self.name = name self.sex = sex self.age = age Jack = Student("Jack", "man", 10) Tom = Student("Tom", "woman", 9) print(vars(Jack)) print(Tom.__dict__) # 输出(dict): {'name': 'Jack', 'sex': 'man', 'age': 10} {'name': 'Tom', 'sex': 'woman', 'age': 9} 使用hasattr()函数判断对象是否包含对应属性 语法:hasattr(object, name) object--对象 name--字符串,属性名 存在该属性返回True,否则返回False

以上面定义的Student类为例

print(hasattr(Tom, 'name')) print(hasattr(Jack, 'score')) #输出 True False


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3